let bookList = [];
let pageNum = 1;
let pageSize = 9;
let pageTotal = 0;
let list = null;
let bookTotal = 0;
let categoryName = $.cookie("categoryName");

function init() {
    if (localStorage.getItem("searchBooks")!==null) {
        initValue(JSON.parse(localStorage.getItem("searchBooks")));
        localStorage.removeItem("searchBooks");
    }else {
        if (categoryName == "") {
            getBooksALl();
        }else {
            getBookByCategory(categoryName);
        }
    }
}

function initValue(books) {
    bookList = books;
    bookTotal = bookList.length;
    pageTotal = Math.ceil(bookTotal/pageSize);
    gotoPage(1);
    for (let i=pageTotal;i>0;i--) {
        if (i === 1) {
            $("ul.umino-pagination-box").prepend("<li class='active'><a href='javascript:void(0)'>" + i + "</a></li>")
        } else {
            $("ul.umino-pagination-box").prepend("<li><a href='javascript:void(0)'>" + i + "</a></li>")
        }
    }
    $("ul.umino-pagination-box li").on("click", function() {
        let ind = Number($(this).find("a").text());
        if (isNaN(ind)) {
            ind = Number($("ul.umino-pagination-box li.active").find("a").text())+1;
        }
        $("ul.umino-pagination-box li").removeClass("active").eq(ind-1).addClass("active")
        gotoPage(ind);
    })
}

function gotoPage(ind) {
    pageNum = ind;
    list = bookList.slice((pageNum-1)*pageSize, pageNum*pageSize);
    $("div.blog-item_wrap").empty();
    list.forEach((book) => {
        let model = getBookTemplate(book);
        $("div.blog-item_wrap").append(model);
    })
    $("div.post-category>ul li").on("click", function() {
        addRelation(this);
        initRelationBook();
    })
}

function addRelation(e) {
    let content = $(e).find("a").text();
    let relation;
    if (content.indexOf("收藏") > -1) {
        relation = "收藏";
    }else if (content.indexOf("购物车") > -1) {
        relation = "购物车";
    }else {
        return false;
    }
    let isbn = $(e).parentsUntil("div.post-category").find("li[name='isbn'] a").text();
    $.ajax({
        type: "POST",
        url: "/api/userBookRelation/u/addUserBookRelation",
        dataType: "text",
        async: false,
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            "bookIsbn": isbn,
            "relation": relation
        }),
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                if (relation == "收藏")
                    alert("收藏成功");
                else if (relation == "购物车")
                    alert("加入购物车成功");
            }else {
                alert(data.msg + ", 请前往购物车或者收藏页面查看");
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    })
}

function getBooksALl() {
    $.ajax({
        type: "GET",
        url: "/api/book/v/getBooksAll",
        processData: false,
        contentType: false,
        success: data => {
            if (data.success) {
                initValue(JSON.parse(data.data));
            } else {
                bookList = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    })
}

function getBookByCategory(categoryName) {
    var formData = new FormData();
    formData.append("categoryName", categoryName);
    $.ajax({
        type: "post",
        url: "/api/book/v/getBookByCategory",
        async: false,
        dataType: "text",
        data: formData,
        processData: false,
        contentType: false,
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                initValue(JSON.parse(data.data));
            }else {
                bookList = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return bookList;
}

function getBookTemplate(book) {
    let reg = new RegExp("\"", "g");
    return "<div class='col-lg-4 col-md-6'>" +
        "<div class='blog-item'>" +
        "<div class='blog-img img-hover_effect'>" +
        "<a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" +
        "<img style='height: 370px; width: auto' class='img-full' src='..//..//images//" + book.bookImg.replace(reg, "") + "' alt='Umino's Blog Image'>" +
        "</a>" +
        "<div class='post-category'>" +
        "<ul>" +
        "<li>" +
        "<a href='javascript:void(0)'>" + book.categoryName + "</a>" +
        "</li>" +
        "<li>" +
        "<a href='javascript:void(0)'>" + book.bookPublishers + "</a>" +
        "</li>" +
        "<li>" +
        "<a href='javascript:void(0)'>" + book.bookPrice + "</a>" +
        "</li>" +
        "<li name='isbn'>" +
        "<a href='javascript:void(0)'>" + book.bookIsbn + "</a>" +
        "</li>" +
        // "<li>" +
        // "<a href='javascript:void(0)'>加入购物车</a>" +
        // "</li>" +
        "<li>" +
        "<a href='javascript:void(0)'>收藏</a>" +
        "</li>" +
        "</ul>" +
        "</div>" +
        "</div>" +
        "<div class='blog-content'>" +
        "<div class='blog-text_area'>" +
        "<div class='title'>" +
        "<h3 style='display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 1;overflow: hidden;'><a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" + book.bookName + "</a></h3>" +
        "</div>" +
        "<div class='meta'>" +
        "<span style='display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 1;overflow: hidden;'>作者: <strong>" + book.bookAuthor + "</strong>/ 出版日期: <strong> " + book.bookTime + " </strong></span>" +
        "</div>" +
        "<div class='short-desc'>" +
        "<p style='display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;overflow: hidden;height: 72px;'> " + book.bookIntroduction + " </p>" +
        "</div>" +
        "<div class='umino-btn-ps_left'>" +
        "<a class='umino-btn_dark' href='bookDetails?bookIsbn=" + book.bookIsbn + "'>详情</a>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>"
}

$(document).ready(function () {
    init();
})